//
//  XQABModel.m
//  SmartCommunity
//
//  Created by ladystyle100 on 2017/5/11.
//  Copyright © 2017年 Ladystyle100. All rights reserved.
//

#import "XQABManager.h"
#import <Contacts/Contacts.h>
#import <AddressBook/AddressBook.h>

/*
 // 照片
 NSData *image = (__bridge NSData*)ABPersonCopyImageData(person);
 //读取middlename
 NSString *middlename = (__bridge NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);
 //读取prefix前缀 (默认是没有的)
 NSString *prefix = (__bridge NSString*)ABRecordCopyValue(person, kABPersonPrefixProperty);
 //读取suffix后缀 (默认是没有的)
 NSString *suffix = (__bridge NSString*)ABRecordCopyValue(person, kABPersonSuffixProperty);
 //读取nickname呢称
 NSString *nickname = (__bridge NSString*)ABRecordCopyValue(person, kABPersonNicknameProperty);
 //读取firstname拼音音标 (默认是没有的)
 NSString *firstnamePhonetic = (__bridge NSString*)ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty);
 //读取lastname拼音音标 (默认是没有的)
 NSString *lastnamePhonetic = (__bridge NSString*)ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty);
 //读取middlename拼音音标
 NSString *middlenamePhonetic = (__bridge NSString*)ABRecordCopyValue(person, kABPersonMiddleNamePhoneticProperty);
 //读取organization公司
 NSString *organization = (__bridge NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty);
 //读取jobtitle工作
 NSString *jobtitle = (__bridge NSString*)ABRecordCopyValue(person, kABPersonJobTitleProperty);
 //读取department部门
 NSString *department = (__bridge NSString*)ABRecordCopyValue(person, kABPersonDepartmentProperty);
 //读取birthday生日
 NSDate *birthday = (__bridge NSDate*)ABRecordCopyValue(person, kABPersonBirthdayProperty);
 //读取note备忘录
 NSString *note = (__bridge NSString*)ABRecordCopyValue(person, kABPersonNoteProperty);
 //第一次添加该条记录的时间
 NSString *firstknow = (__bridge NSString*)ABRecordCopyValue(person, kABPersonCreationDateProperty);
 NSLog(@"第一次添加该条记录的时间%@\n",firstknow);
 //最后一次修改該条记录的时间
 NSString *lastknow = (__bridge NSString*)ABRecordCopyValue(person, kABPersonModificationDateProperty);
 NSLog(@"最后一次修改該条记录的时间%@\n",lastknow);
 
 //获取email多值
 ABMultiValueRef email = ABRecordCopyValue(person, kABPersonEmailProperty);
 int emailcount = ABMultiValueGetCount(email);
 for (int x = 0; x < emailcount; x++)
 {
 //获取email Label
 NSString* emailLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(email, x));
 //获取email值
 NSString* emailContent = (__bridge NSString*)ABMultiValueCopyValueAtIndex(email, x);
 }
 //读取地址多值
 ABMultiValueRef address = ABRecordCopyValue(person, kABPersonAddressProperty);
 int count = ABMultiValueGetCount(address);
 
 for(int j = 0; j < count; j++)
 {
 //获取地址Label
 NSString* addressLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(address, j);
 //获取該label下的地址6属性
 NSDictionary* personaddress =(__bridge NSDictionary*) ABMultiValueCopyValueAtIndex(address, j);
 NSString* country = [personaddress valueForKey:(NSString *)kABPersonAddressCountryKey];
 NSString* city = [personaddress valueForKey:(NSString *)kABPersonAddressCityKey];
 NSString* state = [personaddress valueForKey:(NSString *)kABPersonAddressStateKey];
 NSString* street = [personaddress valueForKey:(NSString *)kABPersonAddressStreetKey];
 NSString* zip = [personaddress valueForKey:(NSString *)kABPersonAddressZIPKey];
 NSString* coutntrycode = [personaddress valueForKey:(NSString *)kABPersonAddressCountryCodeKey];
 }
 
 //获取dates多值
 ABMultiValueRef dates = ABRecordCopyValue(person, kABPersonDateProperty);
 int datescount = ABMultiValueGetCount(dates);
 for (int y = 0; y < datescount; y++)
 {
 //获取dates Label
 NSString* datesLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(dates, y));
 //获取dates值
 NSString* datesContent = (__bridge NSString*)ABMultiValueCopyValueAtIndex(dates, y);
 }
 //获取kind值
 CFNumberRef recordType = ABRecordCopyValue(person, kABPersonKindProperty);
 if (recordType == kABPersonKindOrganization) {
 // it's a company
 NSLog(@"it's a company\n");
 } else {
 // it's a person, resource, or room
 NSLog(@"it's a person, resource, or room\n");
 }
 
 
 //获取IM多值
 ABMultiValueRef instantMessage = ABRecordCopyValue(person, kABPersonInstantMessageProperty);
 for (int l = 1; l < ABMultiValueGetCount(instantMessage); l++)
 {
 //获取IM Label
 NSString* instantMessageLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(instantMessage, l);
 //获取該label下的2属性
 NSDictionary* instantMessageContent =(__bridge NSDictionary*) ABMultiValueCopyValueAtIndex(instantMessage, l);
 NSString* username = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageUsernameKey];
 
 NSString* service = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageServiceKey];
 }
 
 //获取URL多值
 ABMultiValueRef url = ABRecordCopyValue(person, kABPersonURLProperty);
 for (int m = 0; m < ABMultiValueGetCount(url); m++)
 {
 //获取电话Label
 NSString * urlLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(url, m));
 //获取該Label下的电话值
 NSString * urlContent = (__bridge NSString*)ABMultiValueCopyValueAtIndex(url,m);
 }
 */

/** 获取电话Label
 *  home: 住宅
 *  work: 工作
 *  iPhone: iPhone
 *  mobile: 手机
 *  main: 主要
 *  home fax: 住宅传真
 *  work fax: 工作传真
 *  pager: 传呼
 *  other: 其他
 *  自定义标签: 直接显示定义的名字
 */

@interface XQABManager ()

@property (nonatomic, strong) CNContactStore *store;

@property (nonatomic) ABAddressBookRef addressBookRef;

@end

static XQABManager *_manager = nil;

@implementation XQABManager

+ (instancetype)manager {
    if (!_manager) {
        _manager = [XQABManager new];
        _manager.store = [[CNContactStore alloc] init];
        
        //ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
        _manager.addressBookRef = ABAddressBookCreate();
        /** 注册改变回调 */
        ABAddressBookRegisterExternalChangeCallback(_manager.addressBookRef, externalChangeCallback, nil);
        
    }
    return _manager;
}

- (void)dealloc {
    /** 移除回调 */
    ABAddressBookUnregisterExternalChangeCallback(self.addressBookRef, externalChangeCallback, nil);
    /** 释放资源 */
    CFRelease(self.addressBookRef);
}

#pragma mark -- notification 通讯录改变回调

void externalChangeCallback(ABAddressBookRef addressBook, CFDictionaryRef info, void *context) {
    NSLog(@"contact change info = %@, context = %@", info, context);
}

/** 获取当前授权状态 */
+ (XQAuthorizationStatus)getAuStatus {
    return (XQAuthorizationStatus)ABAddressBookGetAuthorizationStatus();
}

/** 请求权限 */
- (void)requestAuStatusWithCompletionHandler:(void (^)(BOOL, NSError * ))completionHandler {
    ABAddressBookRequestAccessWithCompletion(self.addressBookRef, ^(bool granted, CFErrorRef error){
        if (completionHandler) {
            completionHandler(granted, (__bridge NSError *)(error));
        }
    });
}

/** 获取所有联系人 */
- (void)getAllContactWithCompletion:(void(^)(NSArray <XQABModel *> *))completion {
    ABAuthorizationStatus status = (ABAuthorizationStatus)[XQABManager getAuStatus];
    if (status != kABAuthorizationStatusAuthorized) {
        LOG(@"没有权限访问通讯录");
        
        if (!completion) {
            return;
        }
        
        if (status != kABAuthorizationStatusNotDetermined) {
            return;
        }
        
        // 用户没有选择过权限的
        Weak_Self
        [self requestAuStatusWithCompletionHandler:^(BOOL granted, NSError *error) {
            [weakSelf getAllContactWithCompletion:completion];
        }];
        
        return;
    }
    
    /** 回调不在时, 不用调用, 调用没有任何意义 */
    if (!completion) {
        return;
    }
    
    NSMutableArray *modelArr = [NSMutableArray array];
    
    // 获取所有联系人的个数
    CFIndex numberOfPeople = ABAddressBookGetPersonCount(self.addressBookRef);
    // 获取所有联系人
    CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(self.addressBookRef);
    
    for (int i = 0; i < numberOfPeople; i++) {
        // 获取联系人档案
        ABRecordRef person = CFArrayGetValueAtIndex(people, i);
        
        // id
        int recordID = ABRecordGetRecordID(person);
        // 名
        NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
        // 姓
        NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
        // 公司
        NSString *organization = (__bridge NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty);
        // 照片
        NSData *image = (__bridge NSData*)ABPersonCopyImageData(person);
        
        LOG(@"id = %d, 姓 = %@, 名 = %@, 公司 = %@", recordID, lastName, firstName, organization);
        
        NSMutableArray *labelPhoneArr = [NSMutableArray array];
        NSMutableArray *phoneArr = [NSMutableArray array];
        
        // 读取电话多值
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        CFIndex kIndex = ABMultiValueGetCount(phone);
        
        for (int k = 0; k < kIndex; k++) {
            // 获取电话Label
            NSString * personPhoneLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
            // 获取該Label下的电话值
            NSString * personPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);
            
            [labelPhoneArr addObject:personPhoneLabel];
            [phoneArr addObject:personPhone];
            LOG(@"label = %@, phone = %@", personPhoneLabel, personPhone);
        }
        
        CFRelease(phone);
        
        XQABModel *model = [XQABModel new];
        model.contactID = recordID;
        model.lastName = lastName;
        model.firstName = firstName;
        model.organization = organization;
        model.imgData = image;
        model.phoneLabelArr = labelPhoneArr;
        model.phoneArr = phoneArr;
        
        [modelArr addObject:model];
        
    }
    
    completion(modelArr);
    
    CFRelease(people);
}

#pragma mark -- 修改联系人

/** 根据模型修改联系人 */
- (BOOL)modificationContactWithModel:(XQABModel *)model {
    if ([XQABManager getAuStatus] != kABAuthorizationStatusAuthorized) {
        return NO;
    }
    
    ABRecordRef recordRef = ABAddressBookGetPersonWithRecordID(self.addressBookRef, model.contactID);
    
    if (!recordRef) {
        return NO;
    }
    
    BOOL isFirst = ABRecordSetValue(recordRef, kABPersonFirstNameProperty, (__bridge CFTypeRef)(model.firstName), nil);
    BOOL isLast = ABRecordSetValue(recordRef, kABPersonLastNameProperty, (__bridge CFTypeRef)(model.lastName), nil);
    BOOL isOrganization = ABRecordSetValue(recordRef, kABPersonOrganizationProperty, (__bridge CFTypeRef)(model.organization), nil);
    BOOL isImg = ABPersonSetImageData(recordRef, (__bridge CFDataRef)(model.imgData), nil);
    
    // 添加电话
    ABMultiValueRef muVRef = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    for (int i = 0; i < model.phoneArr.count; i++) {
        ABMultiValueAddValueAndLabel(muVRef, (__bridge CFTypeRef)(model.phoneArr[i]), (__bridge CFStringRef)(model.phoneLabelArr[i]), nil);
    }
    BOOL isPhone = ABRecordSetValue(recordRef, kABPersonPhoneProperty, muVRef, nil);
    
    if (!isFirst || !isLast || !isOrganization || !isImg || !isPhone) {
        return NO;
    }
    
    return ABAddressBookSave(self.addressBookRef, nil);
}

/** 修改联系人 */
- (BOOL)modificationContactWithContactID:(int)contactID propertyID:(XQPropertyID)propertyID value:(id)value {
    if ([XQABManager getAuStatus] != kABAuthorizationStatusAuthorized) {
        return NO;
    }
    
    if (propertyID == XQPropertyIDImageData) {
        return [self modificationContactImgWithContactID:contactID imgData:value];
    }
    
    /** 将自己写的id转为系统id */
    ABPropertyID abPID = [XQABManager transfromIDWith:propertyID];
    
    if (abPID == -1) {
        return NO;
    }
    
    ABRecordRef recordRef = ABAddressBookGetPersonWithRecordID(self.addressBookRef, contactID);
    if (!recordRef) {
        return NO;
    }
    
    if (!ABRecordSetValue(recordRef, abPID, (__bridge CFTypeRef)(value), nil)) {
        return NO;
    }
    
    // 保存修改
    return ABAddressBookSave(self.addressBookRef, nil);
}

- (BOOL)modificationContactImgWithContactID:(int)contactID imgData:(NSData *)imgData {
    ABRecordRef recordRef = ABAddressBookGetPersonWithRecordID(self.addressBookRef, contactID);
    BOOL is = ABPersonSetImageData(recordRef, (__bridge CFDataRef)(imgData), nil);
    if (!is) {
        return is;
    }
    
    return ABAddressBookSave(self.addressBookRef, nil);
}

// 修改电话
- (BOOL)modificationContactPhoneWithContactID:(int)contactID phoneLabelArr:(NSArray *)phoneLabelArr phoneArr:(NSArray *)phoneArr {
    if ([XQABManager getAuStatus] != kABAuthorizationStatusAuthorized) {
        return NO;
    }
    
    ABRecordRef recordRef = ABAddressBookGetPersonWithRecordID(self.addressBookRef, contactID);
    // 添加电话
    ABMultiValueRef muVRef = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    for (int i = 0; i < phoneArr.count; i++) {
        ABMultiValueAddValueAndLabel(muVRef, (__bridge CFTypeRef)(phoneArr[i]), (__bridge CFStringRef)(phoneLabelArr[i]), nil);
    }
    
    BOOL is = ABRecordSetValue(recordRef, kABPersonPhoneProperty, muVRef, nil);
    if (!is) {
        return is;
    }
    
    return ABAddressBookSave(self.addressBookRef, nil);
}

#pragma mark -- 添加联系人

// 添加联系人
- (BOOL)addContactWithModel:(XQABModel *)model {
    if ([XQABManager getAuStatus] != kABAuthorizationStatusAuthorized) {
        return NO;
    }
    
    // 创建联系人
    ABRecordRef recordRef = ABPersonCreate();
    // 设置信息
    ABRecordSetValue(recordRef, kABPersonFirstNameProperty, (__bridge CFTypeRef)(model.firstName), nil);
    ABRecordSetValue(recordRef, kABPersonLastNameProperty, (__bridge CFTypeRef)(model.lastName), nil);
    ABRecordSetValue(recordRef, kABPersonOrganizationProperty, (__bridge CFTypeRef)(model.organization), nil);
    ABPersonSetImageData(recordRef, (__bridge CFDataRef)(model.imgData), nil);
    // 添加电话
    ABMultiValueRef muVRef = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    for (int i = 0; i < model.phoneArr.count; i++) {
        ABMultiValueAddValueAndLabel(muVRef, (__bridge CFTypeRef)(model.phoneArr[i]), (__bridge CFStringRef)(model.phoneLabelArr[i]), nil);
    }
    
    ABRecordSetValue(recordRef, kABPersonPhoneProperty, muVRef, nil);
    
    BOOL is = ABAddressBookAddRecord(self.addressBookRef, recordRef, nil);
    if (!is) {
        return NO;
    }
    
    return ABAddressBookSave(self.addressBookRef, nil);
}


#pragma mark -- 删除联系人
// 删除联系人
- (BOOL)removeContactWithContactID:(int)contactID {
    if ([XQABManager getAuStatus] != kABAuthorizationStatusAuthorized) {
        return NO;
    }
    
    ABRecordRef rRef = ABAddressBookGetPersonWithRecordID(self.addressBookRef, contactID);
    BOOL is = ABAddressBookRemoveRecord(self.addressBookRef, rRef, nil);
    if (!is) {
        return is;
    }
    
    return ABAddressBookSave(self.addressBookRef, nil);
}

#pragma mark - Contact 因为用这个SDK取出来的Contact用不了, 所以, 只能先用9.0以前的SDK了

/** 获取授权状态 */
//+ (CNAuthorizationStatus)getAuStatus {
//    return [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
//}

/** 请求授权 */
//- (void)requestAuStatusWithCompletionHandler:(void(^)(BOOL granted, NSError *error))completionHandler {
//    [self.store requestAccessForEntityType:CNEntityTypeContacts completionHandler:completionHandler];
//}

/** 获取所有联系人 */
- (NSError *)enumerateContactsWithFetchRequestWithUsingBlock:(void(^)(CNContact *contact, BOOL *stop))usingBlock {
    NSError *error = nil;
    CNContactFetchRequest *fRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[]];
    // 枚举同步获取
    [self.store enumerateContactsWithFetchRequest:fRequest error:&error usingBlock:usingBlock];
    
    /*
    //设置姓名属性
    self.nickName = contact.nickname;                   //昵称
    self.givenName = contact.givenName;                 //名字
    self.familyName = contact.familyName;               //姓氏
    self.middleName = contact.middleName;               //中间名
    self.namePrefix = contact.namePrefix;               //名字前缀
    self.nameSuffix = contact.nameSuffix;               //名字的后缀
    self.phoneticGivenName = contact.phoneticGivenName; //名字的拼音或音标
    self.phoneticFamilyName = contact.phoneticFamilyName;//姓氏的拼音或音标
    self.phoneticMiddleName = contact.phoneticMiddleName;//中间名的拼音或音标
    
#ifdef __IPHONE_10_0
    self.phoneticOrganizationName = contact.phoneticOrganizationName;//公司(组织)的拼音或音标
#endif
     */
    
    return error;
}

//- (void)aaa {
//    NSError *error = nil;
//    
//    /** 根据标志符获取Contact */
//    CNContact *idenContact = [self.store unifiedContactWithIdentifier:@"" keysToFetch:@[] error:&error];
//    
//    /** 筛选ContactArr */
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@""];
//    NSArray <CNContact *> *contactArr = [self.store unifiedContactsMatchingPredicate:predicate keysToFetch:@[] error:&error];
//    
//    /** 修改联系人 */
//    CNMutableContact *mContact = [idenContact mutableCopy];
//    CNSaveRequest *sRequest = [[CNSaveRequest alloc] init];
//    [sRequest deleteContact:mContact];
//    [self.store executeSaveRequest:sRequest error:&error];
//    
//    /** 改变通知 */
//    //CNContactStoreDidChangeNotification
//}

+ (ABPropertyID)transfromIDWith:(XQPropertyID)propertyID {
    ABPropertyID returnID = -1;
    
    switch (propertyID) {
        case XQPropertyIDFirstName:
            returnID = kABPersonFirstNameProperty;
            break;
        case XQPropertyIDLastName:
            returnID = kABPersonLastNameProperty;
            break;
        case XQPropertyIDOrganization:
            returnID = kABPersonOrganizationProperty;
            break;
            default:
            break;
    }
    
    return returnID;
}


@end

















